import React, { useState, useEffect } from 'react';
import 'antd/dist/antd.css'
import '../css/index.scss'
import { Button, Select, Form, Input, InputNumber, Radio, DatePicker, Table, Space, Cascader,message } from 'antd';
import axios from '../../../../../http/index'

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

export default function Add(props) {
    const [options, setoptions] = useState([])
    const [optionsState, setoptionsState] = useState(1)
    const [options2, setoptions2] = useState([])
    const [optionscopy, setoptionscopy] = useState([])
    const [options2copy, setoptions2copy] = useState([])
    // 指定产品的数据请求
    useEffect(() => {
        axios({
            method: "GET",
            url: '/system/coupon/couponmanagement/queryProduct',
        })
            .then((res) => {
                console.log(res);
                let data = res.data.data

                data = data.map(v => {
                    return { value: v.id, label: v.product_name }
                })
                let datas = [{
                    label: '银行',
                    value: '银行',
                    children: data,
                },]
                console.log(data);
                setoptions([...datas])
                setoptions2([...datas])
                setoptionscopy([...datas])
                setoptions2copy([...datas])
            })
            .catch((err) => {
                console.log(err);
            })
    }, []);

    // 表单数据
    const [data, setdata] = useState({})
    // 
    const onFinish = (values) => {
        console.log(values);
    };
    // 添加弹窗表单的内部内容分布
    const layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
    };
    // 添加弹窗警告提示
    const validateMessages = {
        required: '这是必填项哦',
        types: {
            email: '${label} is not a valid email!',
            number: '${label} is not a valid number!',
        },
        number: {
            range: '${label}必须大于${min}小于${max}',
        },

    };
    // 优惠券类型select下拉
    const { Option } = Select;
    const [select, setSelect] = React.useState('4');
    const [select2, setSelect2] = React.useState('3');

    const onGenderChange = (value) => {
        switch (value) {
            case '1':
                setSelect("")
                setSelect2('')
                return;
            case '2':
                setSelect("")
                setSelect2('')
                return;
            case '3':
                setSelect2('3')
                setSelect("4")
                return;
            case '4':
                setSelect("4")
                setSelect2('')
                return;
        }
    };
    // 优惠券名称
    const couponName = (value) => {

    }
    // 适用平台select下拉
    const onGenderChanges = (value) => {
        switch (value) {
            case '1':
                return;
            case '2':
                return;
            case '3':
                return;
        }
    };

    // 发行量
    const circulation = (value) => {
        console.log(value.target.value);
    }

    // 面额 
    // 去掉2位数以后小数点
    const limitDecimals = (value) => {
        const reg = /^(\-)*(\d+)\.(\d\d).*$/;
        if (typeof value === 'string') {
            return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
        } else if (typeof value === 'number') {
            return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
        } else {
            return ''
        }
    };
    const rmb = (value) => {
        console.log(value);
    }

    // 每人限领
    const limits = e => {
        console.log(e.target.value);
    }

    // 使用门槛单选
    const [useThreshold, setuseThreshold] = React.useState(1);
    const singleChoice = e => {

        console.log('radio checked', e.target.value);
        setuseThreshold(e.target.value);
    };
    // 使用门槛input输入框
    const product = e => {
        setdata((data) => {
            return { ...data, product: e.target.value }
        })
    }


    // 日期选择器
    const { RangePicker } = DatePicker;
    function onChange(value, dateString) {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        setdata({ ...data, timer: dateString })
    }

    function onOk(value) {
        console.log('onOk: ', value);
    }

    // 表格
    const columns = [
        {
            title: '产品名称',
            dataIndex: 'address',
            align: 'center',
        },
        {
            title: '货号',
            dataIndex: 'key',
            align: 'center',
        },
        {
            title: '操作',
            dataIndex: 'key',
            align: 'center',
            render: text => <div><Button size="small" onClick={() => del(text)}>删除</Button></div>,
        },
    ];


    // 表格假数据
    const [tables, stetables] = useState([])

    // 表格数据删除
    const del = (text) => {
        let s = tables.filter((item) => item.key != text)
        stetables(s)
        setdata({ ...data, datas: tables })

    }

    // 可使用产品单选按钮
    const [usableProducts, modifyProducts] = React.useState('1');
    const singleChoices = e => {
        if (usableProducts === '1') {
            stetables([])
        }
        console.log('radio checked', e.target.value);
        modifyProducts(e.target.value);
    };

    // 可使用产品单选按钮内联级下拉框
    function classification(value) {
        let s = options[0].children
        console.log(s);
        if (value.length == 0) {
            return
        }
        if (value[0].length > 1) {

            for (let i = 0; i < value.length; i++) {

                for (let j = 0; j < s.length; j++) {

                    if (value[i][1] == s[j].value) {

                        console.log('123', value[i][1], s[j].label);

                        if (!tables.some((item) => {
                            return value[i][1] == item.key
                        })) {

                            stetables([...tables,
                            {
                                key: value[i][1],
                                name: value[i][1],
                                address: s[j].label,
                            }
                            ])
                        }

                    }
                }
            }
        } else {

            s.forEach((e) => {

                if (!tables.some((item) => {
                    return e.value == item.key
                })) {
                    stetables((tables) => {
                        return [...tables,
                        {
                            key: e.value,
                            name: e.value,
                            address: e.label,
                        }
                        ]
                    })
                }
            })
        }
        console.log('1', value);
    }
    function classificationcopy(value) {
        console.log('2', value);
    }
    // 获取门槛
    const threshold = e => {
        console.log(e.target.value);
    }

    // 可赠卷产品单选按钮
    const [couponFreeProducts, setcouponFreeProducts] = React.useState('1');
    const singleChoices2 = e => {
        console.log('radio checked', e.target.value);
        setcouponFreeProducts(e.target.value);
    };
    // 可赠卷产品单选按钮内联级下拉框

    function classification2(value) {
        console.log(value);
    }
    function classification2copy(value) {
        console.log(value);
    }

    // 会员单选按钮
    const [member, modifymember] = React.useState(1);
    const memberradio = e => {
        console.log('radio checked', e.target.value);
        modifymember(e.target.value);
    };

    // 备注
    const introduction = e => {
        console.log(e.target.value);
    }

    // 提交数据
    const [form] = Form.useForm();
    const onCheck = async () => {
        try {
            const values = await form.validateFields();
            // setdata((data) => {
            //     return {...data,datas:tables}
            // })
            let a = []
            if (usableProducts !== '1') {
                values.adsadss.forEach((item) => { a.push(item[1]) })
            }
            console.log('adas', data);
            console.log('Success:', values);
            axios({
                method:'GET',
                url:'/system/coupon/couponmanagement/addCoupon',
                params:{
                    acquisition_threshold: values.threshold,
                    add_product: values.product2 === '2' ? a.join(',') : '',
                    applicable_platform: String(values.applicationPlatform),
                    chelpcenteroupon_name: values.couponName,
                    coupon_products: values.product2 === '2' ? a.join(',') : '2',
                    coupon_type: String(values.gender),
                    face_value: String(values.rmbs),
                    limited_person: String(values.limits),
                    participating_members: String(values.product4),
                    remarks: values.introduction,
                    term_validity: data.timer.join('到'),
                    total_circulation: String(values.circulation),
                    usable_products: String(values.product2),
                    use_threshold: values.product === 1 ? '1' : data.product,
                }
            })
            .then((res) => {
                message.success('添加成功');
                console.log(132,res);
                props.close1()
                props.seedata()
            })
            .catch((err) => {
                console.log(132,err);
                message.error('添加失败');
            })
        } catch (errorInfo) {
            console.log('Failed:', errorInfo);
        }
    };
    return (
        <div>
            <Form {...layout} name="nest-messages"
                onFinish={onFinish}
                validateMessages={validateMessages}
                initialValues={{
                    gender: '3',
                    applicationPlatform: '1',
                    product: 1,
                    product2: "1",
                    product3: "1",
                    product4: "1",
                    rmbs: 10,
                    circulation: 1,
                    limits: 1,
                }}
                form={form}
            >
                <Form.Item
                    name="gender"
                    label="优惠券类型"

                >
                    <Select
                        placeholder="请选择优惠券类型"
                        onChange={onGenderChange}
                        allowClear
                        style={{ width: '75%' }}
                        getPopupContainer={triggerNode => triggerNode.parentNode}

                    >
                        <Option value="1">注册赠卷</Option>
                        <Option value="2">全场赠卷</Option>
                        <Option value="3">申贷赠卷</Option>
                        <Option value="4">会员赠卷</Option>
                    </Select>
                </Form.Item>


                <Form.Item name='couponName' label="优惠券名称" rules={[{ required: true }]}>
                    <Input onBlur={couponName} placeholder="请输入优惠券名称" style={{ width: '75%' }} />
                </Form.Item>


                <Form.Item
                    name="applicationPlatform"
                    label="适用平台"
                >
                    <Select
                        placeholder="请选择优惠卷适用平台"
                        onChange={onGenderChanges}
                        allowClear
                        style={{ width: '75%' }}
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                    >
                        <Option value="1">全场通用</Option>
                        <Option value="2">指定产品</Option>
                        <Option value="3">指定分类</Option>
                    </Select>
                </Form.Item>


                <Form.Item name='circulation' label="总发行量" rules={[{ type: 'number', min: 1, max: 999999999999 }]}>
                    <InputNumber style={{ width: '50%' }} addonAfter="张" onBlur={circulation} placeholder="请填写有效数字" />
                </Form.Item>


                <Form.Item name='rmbs' label="面额" rules={[{ type: 'number', min: 0, max: 999999999999 }]}>
                    <InputNumber
                        onBlur={rmb}
                        step={0.01}
                        formatter={limitDecimals}
                        parser={limitDecimals}
                        prefix="￥"
                        style={{ width: '50%' }}
                        addonAfter="元"
                        controls={false}
                        placeholder="精确到2位小数"
                    />
                </Form.Item>

                <Form.Item name='limits' label="每人限领" rules={[{ type: 'number', min: 1, max: 999999999999 }]}>
                    <InputNumber style={{ width: '50%' }} addonAfter="张" onBlur={limits} placeholder="请填写有效数字" />
                </Form.Item>


                <Form.Item name='product' label="使用门槛" >
                    <Radio.Group onChange={singleChoice}>
                        <Radio value={1}>无限制</Radio>
                        <Radio value={2}>
                            满<Input onBlur={product} style={{ width: 100, marginLeft: 10 }} readOnly={useThreshold === 2 ? false : true} /> 元可用
                        </Radio>
                    </Radio.Group>
                </Form.Item>


                <Form.Item name='timer' label="有效期" rules={[{ required: true }]}>
                    <RangePicker
                        showTime={{ format: 'HH:mm' }}
                        format="YYYY-MM-DD HH:mm"
                        onChange={onChange}
                        onOk={onOk}
                        locale={locale}
                    />
                </Form.Item>

                <Form.Item name='product2' label="可使用产品">
                    <Radio.Group onChange={singleChoices}>
                        <Radio value="1">全场通用</Radio>
                        <Radio value="2">指定产品</Radio>
                        <Radio value="3">指定分类</Radio>

                    </Radio.Group>
                </Form.Item>
                {
                    usableProducts !== "1" ?
                        <div>
                            <Form.Item name="adsadss" label="添加产品" >
                                {usableProducts === '2' ?
                                    <Cascader
                                        onDropdownVisibleChange={(value) => {
                                            if (value) {
                                                setoptionsState(2)
                                            } else {
                                                setoptionsState(1)
                                            }
                                        }}
                                        style={{ width: '75%' }}
                                        options={options}
                                        onChange={classification}
                                        multiple
                                        maxTagCount="responsive"
                                        placeholder="请选择产品"
                                        getPopupContainer={triggerNode => triggerNode.parentNode}
                                    />
                                    :
                                    <Cascader
                                        onDropdownVisibleChange={(value) => {
                                            if (value) {
                                                setoptionsState(2)
                                            } else {
                                                setoptionsState(1)
                                            }
                                        }}
                                        style={{ width: '75%' }}
                                        options={optionscopy}
                                        onChange={classificationcopy}
                                        multiple
                                        maxTagCount="responsive"
                                        placeholder="请选择产品"
                                        getPopupContainer={triggerNode => triggerNode.parentNode}
                                    />
                                }
                            </Form.Item>

                            <div className={[optionsState == 2 ? 'hasTop' : ''].join(' ')}>
                                <Form.Item name="adsadss" label="产品列表">
                                    <Table style={{ width: '75%' }} bordered columns={columns} dataSource={tables} />
                                </Form.Item>
                            </div>
                        </div>

                        : null
                }

                {select2 === '3' ?
                    <div>
                        <Form.Item name='threshold' label="获取门槛" rules={[{ required: true }]}>
                            <span>商品满<Input onBlur={threshold} style={{ width: 100, marginLeft: 10 }} /> 元可用优惠券</span>
                        </Form.Item>


                        <Form.Item name='product3' label="可赠券产品">
                            <Radio.Group onChange={singleChoices2}>
                                <Radio value="1">全场通用</Radio>
                                <Radio value="2">指定产品</Radio>
                                <Radio value="3">指定分类</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {
                            couponFreeProducts !== "1" ?
                                <div style={{ marginTop: 20 }}>
                                    <Form.Item name='addProduct2' label="添加产品">
                                        {couponFreeProducts === '2' ?
                                            <Cascader
                                                onDropdownVisibleChange={(value) => {
                                                    if (value) {
                                                        setoptionsState(2)
                                                    } else {
                                                        setoptionsState(1)
                                                    }
                                                }}
                                                style={{ width: '75%' }}
                                                options={options2}
                                                onChange={classification}
                                                multiple
                                                maxTagCount="responsive"
                                                placeholder="请选择产品"
                                                getPopupContainer={triggerNode => triggerNode.parentNode}
                                            />
                                            :
                                            <Cascader
                                                onDropdownVisibleChange={(value) => {
                                                    if (value) {
                                                        setoptionsState(2)
                                                    } else {
                                                        setoptionsState(1)
                                                    }
                                                }}
                                                style={{ width: '75%' }}
                                                options={options2copy}
                                                onChange={classificationcopy}
                                                multiple
                                                maxTagCount="responsive"
                                                placeholder="请选择产品"
                                                getPopupContainer={triggerNode => triggerNode.parentNode}
                                            />
                                        }
                                    </Form.Item>
                                    <div className={[optionsState == 2 ? 'hasTop' : ''].join(' ')}>
                                        <Form.Item name="adsadss" label="产品列表" >
                                            <Table style={{ width: '75%', }} bordered columns={columns} dataSource={tables} />
                                        </Form.Item>
                                    </div>
                                </div>
                                : null
                        }
                    </div>
                    :
                    null
                }



                {select === '4' ?
                    <Form.Item name='product4' label="参与会员">
                        <Radio.Group onChange={memberradio}>
                            <Radio value="1">全部会员</Radio>
                            <Radio value="2">普通会员</Radio>
                            <Radio value="3">黄金会员</Radio>
                            <Radio value="4">钻石会员</Radio>
                        </Radio.Group>
                    </Form.Item>
                    : null
                }



                <Form.Item name='introduction' label="备注"  >
                    <Input.TextArea style={{ width: '75%', height: 100 }} onBlur={introduction} />
                </Form.Item>


                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                    <Button type="primary" htmlType="submit" onClick={onCheck}>
                        提交
                    </Button>
                </Form.Item>

            </Form>

        </div>
    )
}
